package com.ias.log.util;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常工具类
 * 
 * @author ias
 * @since 2024
 */
public class ExcpUtil {

    /**
     * 获取异常堆栈信息（截取前500个字符）
     *
     * @param e 异常对象
     * @return 异常堆栈信息
     */
    public static String getSubStackTrace(Throwable e) {
        if (e == null) {
            return "";
        }
        String stackTrace = getStackTrace(e);
        if (stackTrace != null && stackTrace.length() > 500) {
            return stackTrace.substring(0, 500);
        }
        return stackTrace;
    }

    /**
     * 获取完整的异常堆栈信息
     *
     * @param e 异常对象
     * @return 异常堆栈信息
     */
    public static String getStackTrace(Throwable e) {
        if (e == null) {
            return "";
        }
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            e.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }

    /**
     * 获取异常的根本原因
     *
     * @param e 异常对象
     * @return 根本原因异常
     */
    public static Throwable getRootCause(Throwable e) {
        if (e == null) {
            return null;
        }
        Throwable cause = e;
        while (cause.getCause() != null) {
            cause = cause.getCause();
        }
        return cause;
    }
}

